<?php

/**
 * 企业微信API
 */
class WorkWechat {

    /**
     * @var string 企业微信的企业ID
     */
    private static $corpId = "ww5187d4cc7bffa8a3";

    /**
     * @var string 应用ID
     */
    private static $agentId = "1000003";

    /**
     * @var string 应用的Secret
     */
    private static $corpSecret = "iNUUTbVqsn_AMWUyWNV5PvfgODfr7kibCZEFBwfzAqA";

    /**
     * 获取AccessToken
     * @param bool $forceRefresh 是否强制刷新
     * @return string
     */
    private static function getAccessToken( $forceRefresh ){
        $cacheKey = "ACCESS_TOKEN_AGENT_".self::$agentId;
        $cacheVal = S($cacheKey);
        if( !empty($cacheVal) && $forceRefresh == false ){
            return $cacheVal;
        }
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s';
        $url = sprintf($url,self::$corpId,self::$corpSecret);
        $response = file_get_contents($url);
        $result = json_decode($response,true);
        if( isset($result['access_token']) && !empty($result['access_token']) ){
            S($cacheKey,$result['access_token'],7000);
            return $result['access_token'];
        }
        return null;
    }

    /**
     * @param string $type 消息类型【markdown|text】
     * @param string $content 内容
     * @param bool $forceRefresh 是否强制刷新
     * @return bool
     */
    public static function appChatSendMessage($chatid, $type, $content, $forceRefresh) {
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=%s';
        $url = sprintf($url,self::getAccessToken($forceRefresh));
        $param = array();
        $param['safe'] = 0;
        $param['chatid'] = $chatid;
        if( $type == 'markdown' ){
            $param['msgtype'] = 'markdown';
            $param['markdown'] = array("content" => $content);
        }elseif( $type == 'text' ){
            $param['msgtype'] = 'text';
            $param['text'] = array("content" => $content);
        }
        $response = self::httpRequest($url, $param, "POST");
        if( strpos($response,'invalid_access_token') ){
            return self::appChatSendMessage($chatid, $type, $content, true);
        }
        $result = json_decode($response, true);
        if( $result['errcode'] == 0 ){
            return true;
        }
        return false;
    }

    /**
     * 发起http请求
     * @param $url 请求地址
     * @param array $param 请求参数
     * @param string $type 请求类型 【GET|POST】
     * @param array $header 请求头
     * @return bool|mixed|string
     */
	private static function httpRequest( $url, $param = array(), $type = 'POST', $header = array() ) {
        $ch = curl_init();
        //设置url
        curl_setopt($ch,CURLOPT_URL,$url);
        //1)设置请求头
        array_push($header,'Content-Type:application/json');
        //设置为false,只会获得响应的正文(true的话会连响应头一并获取到)
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt ( $ch, CURLOPT_TIMEOUT,5); // 设置超时限制防止死循环
        //设置发起连接前的等待时间，如果设置为0，则无限等待。
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
        //将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //2)设备请求体
        if( count($param) > 0 ){
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($param));//全部数据使用HTTP协议中的"POST"操作来发送。
        }
        //设置请求头
        if( count($header) > 0 ){
            curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        }
        //上传文件相关设置
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);// 从证书中检查SSL加密算
        if($type == "GET"){
            curl_setopt($ch,CURLOPT_HTTPGET,true);
        }
        if($type == "POST"){
            curl_setopt($ch,CURLOPT_POST,true);
        }
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
	}
}

?>